using System;
using System.Collections.Generic;
using System.Text;

namespace Universe.Farm.Service
{
    class TimeStamp: IComparable<TimeStamp>
    {
        public static readonly int Size = 16;
        private byte[] _value = new byte[Size];


        public TimeStamp()
        {
        }

        public static TimeStamp Zero
        {
            get
            {
                return new TimeStamp();
            }
            
        }

        public int CompareTo(TimeStamp other)
        {
            if (other == null)
                return 1;

            else
            {
                for(int i=Size-1; i>=0; i--)
                {
                    int ret = (int) this._value[i] - (int) other._value[i];
                    if (ret != 0)
                        return ret;
                }

                return 0;
            }
        }

        public void Inc()
        {
            int index = 0;
            lock (_value)
            {
                while (true)
                {
                    if (_value[index] < byte.MaxValue)
                    {
                        _value[index] = (byte) (_value[index] + 1);
                        return;
                    }

                    else
                    {
                        _value[index] = 0;
                        index++;
                        if (index == Size)
                            throw new IndexOutOfRangeException("Timestamp Overflow");
                    }
                }
            }
        }


        public override string ToString()
        {
            StringBuilder ret = new StringBuilder();
            for (int i = 0; i < _value.Length; i++)
                ret.Append(i%4 == 0 && i > 0 ? "-" : "").Append(_value[i].ToString("X2"));

            return ret.ToString();
        }

        public byte[] Serialize()
        {
            return _value;
        }

        public static TimeStamp Parse(byte[] bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException("bytes");

            if (bytes.Length != Size)
                throw new ArgumentException("bytes.Length requires " + Size  + " bytes");

            TimeStamp ret = new TimeStamp();
            ret._value = bytes;
            return ret;
        }
    }
}